﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tenta_2014_12_14_5
{
    class HT<TValue> where TValue : class
    {
        private LinkedList<TValue> list;
        private Node<TValue>[] table;
        public HT(int size = 97)
        {
            list = new LinkedList<TValue>(size);
            table = new Node<TValue>[size];
            for (int i = 0; i < size; i++)
                table[i] = null;
        }

        public void Print()
        {
            list.Print(table.Count());
        }

        public Node<TValue> Search(TValue data)
        {
            int index = Math.Abs(data.GetHashCode() % table.Count());
            return table[index];
        }
        public Node<TValue> Search(string data)
        {
            int index = Math.Abs(data.GetHashCode() % table.Count());
            return table[index];
        }

        public void Add(TValue data)
        {
            int index = Math.Abs(data.GetHashCode() % table.Count());
            if (table[index] != null)
            {
                Node<TValue> n = table[index];
                while (n.Next != null)
                {
                    if (Math.Abs(n.Next.Data.GetHashCode() % table.Count()) == index)
                        n = n.Next;
                    else
                        break;
                }
                table[index] = list.Insert(data, n);
            }
            else
            {
                if (index == 0)
                {
                    table[index] = list.InsertAtHead(data);
                }
                else
                {
                    int i = 1;
                    while (table[index - i] == null)
                    {
                        i++;
                        if (index - i < 0)
                            break;
                    }
                    if (index - i < 0)
                        table[index] = list.InsertAtHead(data);
                    else
                    {
                        Node<TValue> n = table[index - i];
                        while (n.Next != null)
                        {
                            if (Math.Abs(n.Next.Data.GetHashCode() % table.Count()) == index - i)
                                n = n.Next;
                            else
                                break;
                        }
                        table[index] = list.Insert(data, n);
                    } 
                }
            }
        }
    }
}
